import axios from 'axios'
import { ElMessage } from 'element-plus'

const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 自动添加token
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    console.error('API请求错误:', error)
    
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
      ElMessage.error('登录已过期，请重新登录')
      window.location.href = '/login'
    }
    
    return Promise.reject(error)
  }
)

// 主机管理
export const hostAPI = {
  list: (params) => api.get('/hosts/', { params }),
  get: (id) => api.get(`/hosts/${id}/`),
  create: (data) => api.post('/hosts/', data),
  update: (id, data) => api.put(`/hosts/${id}/`, data),
  delete: (id) => api.delete(`/hosts/${id}/`),
  stats: () => api.get('/hosts/stats/'),
  checkStatus: (id) => api.get(`/hosts/${id}/check_status/`),
  checkAllStatus: () => api.post('/hosts/check_all_status/'),
  export: () => api.get('/hosts/export/', { responseType: 'blob' }),
  import: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return api.post('/hosts/import/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  monitor: (id) => api.get(`/hosts/${id}/monitor/`)
}

// 主机组管理
export const hostGroupAPI = {
  list: (params) => api.get('/host-groups/', { params }),
  get: (id) => api.get(`/host-groups/${id}/`),
  create: (data) => api.post('/host-groups/', data),
  update: (id, data) => api.put(`/host-groups/${id}/`, data),
  delete: (id) => api.delete(`/host-groups/${id}/`)
}

// 项目管理
export const projectAPI = {
  list: (params) => api.get('/projects/', { params }),
  get: (id) => api.get(`/projects/${id}/`),
  create: (data) => api.post('/projects/', data),
  update: (id, data) => api.put(`/projects/${id}/`, data),
  delete: (id) => api.delete(`/projects/${id}/`)
}

// 环境管理
export const environmentAPI = {
  list: (params) => api.get('/environments/', { params }),
  get: (id) => api.get(`/environments/${id}/`),
  create: (data) => api.post('/environments/', data),
  update: (id, data) => api.put(`/environments/${id}/`, data),
  delete: (id) => api.delete(`/environments/${id}/`),
  byProject: (projectId) => api.get(`/environments/by_project/?project_id=${projectId}`)
}

// 用户管理
export const userAPI = {
  list: (params) => api.get('/users/', { params }),
  get: (id) => api.get(`/users/${id}/`),
  create: (data) => api.post('/users/', data),
  update: (id, data) => api.put(`/users/${id}/`, data),
  delete: (id) => api.delete(`/users/${id}/`)
}

// 用户组管理
export const userGroupAPI = {
  list: (params) => api.get('/user-groups/', { params }),
  get: (id) => api.get(`/user-groups/${id}/`),
  create: (data) => api.post('/user-groups/', data),
  update: (id, data) => api.put(`/user-groups/${id}/`, data),
  delete: (id) => api.delete(`/user-groups/${id}/`)
}

// 认证管理
export const authAPI = {
  login: (data) => api.post('/auth/login/', data),
  register: (data) => api.post('/auth/register/', data),
  logout: (data) => api.post('/auth/logout/', data),
  currentUser: () => api.get('/auth/current-user/'),
  updateProfile: (data) => api.put('/auth/update-profile/', data),
  uploadAvatar: (file) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return api.post('/auth/upload-avatar/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  changePassword: (data) => api.post('/auth/change-password/', data)
}

// 系统巡检
export const inspectionAPI = {
  getInspectionData: () => api.get('/inspection/'),
  sendEmail: (data) => api.post('/inspection/', data)
}

// 收件人管理
export const recipientAPI = {
  list: (params) => api.get('/recipients/', { params }),
  get: (id) => api.get(`/recipients/${id}/`),
  create: (data) => api.post('/recipients/', data),
  update: (id, data) => api.put(`/recipients/${id}/`, data),
  delete: (id) => api.delete(`/recipients/${id}/`)
}

export default api
